<template>
  <page-form-row>
    <page-form-item field="orderSource" label="订单来源">
      <a-select placeholder="请选择" v-model="form.orderSource" :disabled="mode == 'editOrder' || isProgress">
        <a-option v-for="item in orderSourceEnum" :key="item.value" :label="item.label" :value="item.value" />
      </a-select>
    </page-form-item>
    <page-form-item field="orderAcquisitionType" label="订单获取方式">
      <sysdict-select
        v-model="form.orderAcquisitionType"
        allow-clear
        allow-search
        code="short_order_acquisition_type"
        @change="changeOrderAcquisitionTypeFn"
      />
    </page-form-item>
    <page-form-item field="timeRange" label="预计租赁周期" labelTooltipContent="最短租赁周期为1个月">
      <template #label-extra>
        <div class="rent-days"> 租期：{{ form.rentDays || '- 天' }} </div>
      </template>
      <i-range-picker
        :disabled="isProgress"
        v-model="form.timeRange"
        shortcuts-position="left"
        :shortcuts="rangeShortcuts"
        class="w-full"
        @change="(val) => changeTimeRange(val, item)"
        @selectShortcut="selectShortcutFn"
      />
    </page-form-item>
    <page-form-item field="siteId" label="取车门店">
      <template #label-extra>
        <a-checkbox v-model="form.sendServiceFlag" :disabled="sendServiceFlagDisabled || isProgress" @change.stop>上门送车</a-checkbox>
      </template>
      <remote-select
        :disabled="isProgress"
        v-model="form.siteId"
        :params="{ oldId: form.siteId, siteStatusList: [10] }"
        type="site_listBystaff"
        :allow-clear="false"
        @change="(val) => changeSiteIdFn(val, 'site')"
      />
    </page-form-item>
    <page-form-item label="还车门店">
      <template #label-extra>
        <a-checkbox v-model="form.returnServiceFlag" :disabled="returnServiceFlagDisabled">上门取车</a-checkbox>
      </template>
      <remote-select
        v-model="form.returnSiteId"
        :params="{ siteType: 40, siteId: form.siteId, siteStatusList: [10] }"
        type="site_lease_list_long"
        :allow-clear="false"
        @change="(val) => changeSiteIdFn(val, 'returnSite')"
        @listGet="returnSiteListGetFn"
      />
    </page-form-item>
    <page-form-item field="originalModelId" label="车型" labelTooltipContent="请先选择租赁周期和取车门店后，再选择车型">
      <select-input
        :disable="!form.rentDays || !form.siteId || isProgress"
        v-model="form.originalModelName"
        @clear="clearCarModelFn"
        @click="selectCarModelFn"
      />
    </page-form-item>
    <page-form-item field="address" label="上门送车地址">
      <template #label-extra>
        <div class="map-location" :class="[!form.sendServiceFlag ? 'disabled' : '']" @click="mapLocationClickFn('address')">
          <icon-location /> 地图选择
        </div>
      </template>
      <lease-auto-complete
        :disabled="!form.sendServiceFlag || isProgress"
        v-model="form.address"
        @change="(point) => autoCompleteChangeFn(point, 'address')"
        @blur="updateLnglatPickerTips('address')"
      />
    </page-form-item>
    <page-form-item field="returnAddress" label="上门取车地址">
      <template #label-extra>
        <div class="map-location" :class="[!form.returnServiceFlag ? 'disabled' : '']" @click="mapLocationClickFn('returnAddress')">
          <icon-location /> 地图选择
        </div>
      </template>
      <lease-auto-complete
        :disabled="!form.returnServiceFlag"
        v-model="form.returnAddress"
        @change="(point) => autoCompleteChangeFn(point, 'returnAddress')"
        @blur="updateLnglatPickerTips('returnAddress')"
      />
    </page-form-item>
    <page-form-item label="订单备注" size="2/3" class="mb-0">
      <i-textarea v-model="form.remark" />
    </page-form-item>
  </page-form-row>

  <!-- 坐标选择 -->
  <lnglat-picker-modal title="地图选择" ref="lnglatPickerModalRef" @change="mapLocationSuccessFn" />
  <!-- 车型选择 -->
  <car-model-selector ref="carModelSelectorRef" @confirm="carModelConfirmFn" />
</template>
<script setup>
  import { ref, inject, computed, nextTick } from 'vue'
  import { getSiteLeaseDetail } from '@/api/asset/site'
  import { computeRentDay, calcDate } from '@/api/order/czsOrder'
  import carModelSelector from '@/views/assets/car/stock/car-model-selector.vue'
  import leaseAutoComplete from './lease-auto-complete.vue'
  import iTextarea from '@/views/order/long-order/components/i-textarea.vue'
  import selectInput from './select-input.vue'
  import dayjs from 'dayjs'
  import { Modal, Message } from '@arco-design/web-vue'

  const rangeShortcuts = [
    {
      label: '一个月',
    },
    {
      label: '三个月',
    },
    {
      label: '半年',
    },
    {
      label: '1年',
    },
    {
      label: '2年',
    },
  ]
  // 点击快捷筛选
  const selectShortcutFn = (shortcut) => {
    let cacheStart = form.value.expectedUseCarTime
    let cacheEnd = form.value.expectedReturnCarTime
    nextTick(() => {
      // 移除副作用 start
      formRef.value.clearValidate('timeRange')
      form.value.timeRange = [cacheStart, cacheEnd]
      form.value.expectedUseCarTime = cacheStart
      form.value.expectedReturnCarTime = cacheEnd
      // 移除副作用 end
    })
    quickDateItemClicked(shortcut.label).then((val) => {
      let startStr = val[0]
      let endStr = val[1]
      form.value.expectedUseCarTime = startStr
      form.value.expectedReturnCarTime = endStr
      form.value.timeRange = [startStr, endStr]
      // changeTimeRange(form.value.timeRange)
      changeTimeRange(form.value.timeRange)
    })
  }
  // 快捷筛选调用接口
  const quickDateItemClicked = (type) => {
    return new Promise((resolve) => {
      const param = {
        startDateTime: dayjs().format('YYYY-MM-DD 00:00:00'),
      }
      switch (type) {
        case '一个月':
          param.addMonths = 1
          break
        case '三个月':
          param.addMonths = 3
          break
        case '半年':
          param.addMonths = 6
          break
        case '1年':
          param.addYears = 1
          break
        case '2年':
          param.addYears = 2
          break
      }
      calcDate(param).then((res) => {
        let startStr = param.startDateTime
        let endStr = res.result
        resolve([startStr, endStr])
      })
    })
  }
  const changeOrderAcquisitionTypeFn = (a, option = {}) => {
    if (option) {
      form.value.orderAcquisitionName = option.name
    } else {
      form.value.orderAcquisitionName = ''
    }
  }
  // 列表页，修改承租人信息时 isListEditMember 传为 true
  const props = defineProps({
    // 场景
    mode: {
      type: String,
      default: 'createOrder', // editLesseeMemberModal （编辑承租人弹窗）| createOrder（创建订单）| editOrder（编辑订单）
    },
    isProgress: {
      type: Boolean,
      default: false, // editLesseeMemberModal （编辑承租人弹窗）| createOrder（创建订单）| editOrder（编辑订单）
    },
  })

  const emit = defineEmits(['calcPriceFn', 'timeRangeChange'])
  const form = inject('form')
  const formRef = inject('formRef')
  const formDisabled = inject('formDisabled')
  // const dict = inject('dict')
  const orderSourceEnum = [{ value: 1, label: '线下订单', disabled: false }]
  const changeTimeRange = (value = []) => {
    if (value[0] && value[1]) {
      // 计算租期
      const param = {
        expectedUseCarTime: dayjs(value[0]).format('YYYY-MM-DD 00:00:00'),
        expectedReturnCarTime: dayjs(value[1]).format('YYYY-MM-DD 23:59:59'),
      }
      form.value.timeRange = [param.expectedUseCarTime, param.expectedReturnCarTime]
      form.value.expectedUseCarTime = param.expectedUseCarTime
      form.value.expectedReturnCarTime = param.expectedReturnCarTime
      computeRentDay(param).then((res) => {
        let { result } = res
        form.value.rentDays = result.dateStr
        form.value.leaseNumberStr = result.dateStr
        form.value.rentMonths = result.months
        if (result.months > 0) {
          if (props.mode == 'editOrder') {
            emit('timeRangeChange', value)
            // Modal.confirm({
            //   title: '确认',
            //   content: '预计租赁周期变更，不影响租车费及账单计划分期，请到订单详情-费用信息页面修改费用及账单分期，请确认是否修改？',
            //   okText: '确认',
            //   cancelText: '关闭',
            //   onOk: () => {
            //     emit('timeRangeChange', value)
            //   },
            // })
          }
        }
      })
      formRef.value.clearValidate('timeRange')
      emit('calcPriceFn')
    } else {
      form.value.rentDays = undefined
      form.value.leaseNumberStr = undefined
    }
  }
  // 地图选点
  const lnglatPickerModalRef = ref()
  const lnglatPickerType = ref('')
  const mapLocationClickFn = (type) => {
    if (formDisabled) return
    if ((type == 'address' && form.value.sendServiceFlag) || (type == 'returnAddress' && form.value.returnServiceFlag)) {
      lnglatPickerType.value = type
      let lnglat = []
      if (type == 'address') {
        if (form.value.longitude && form.value.latitude) lnglat = [form.value.longitude, form.value.latitude]
      } else {
        if (form.value.returnLongitude && form.value.returnLatitude) lnglat = [form.value.returnLongitude, form.value.returnLatitude]
      }
      if (lnglat.length > 0) {
        lnglatPickerModalRef.value.open(lnglat.join(','))
      } else {
        lnglatPickerModalRef.value.open()
      }
    }
  }
  // 地图选点结束
  const mapLocationSuccessFn = (lnglat, option) => {
    if (lnglatPickerType.value == 'address') {
      form.value.longitude = lnglat[0]
      form.value.latitude = lnglat[1]
      form.value.address = option.formattedAddress
    } else {
      form.value.returnLongitude = lnglat[0]
      form.value.returnLatitude = lnglat[1]
      form.value.returnAddress = option.formattedAddress
    }
    // 更新 field 提示
    updateLnglatPickerTips(lnglatPickerType.value)
  }
  // 地点输入回调
  const autoCompleteChangeFn = (lnglat, type) => {
    if (!lnglat) {
      if (type == 'address') {
        form.value.longitude = undefined
        form.value.latitude = undefined
      } else {
        form.value.returnLongitude = undefined
        form.value.returnLatitude = undefined
      }
    } else {
      if (type == 'address') {
        form.value.longitude = lnglat[0]
        form.value.latitude = lnglat[1]
      } else {
        form.value.returnLongitude = lnglat[0]
        form.value.returnLatitude = lnglat[1]
      }
      // 更新 field 提示
      updateLnglatPickerTips(type)
    }
  }
  // 更新地址提示
  const updateLnglatPickerTips = (type) => {
    let formVal = form.value
    let longitudeProp = ''
    let latitudeProp = ''
    if (type == 'address') {
      longitudeProp = 'longitude'
      latitudeProp = 'latitude'
    }
    if (type == 'returnAddress') {
      longitudeProp = 'returnLongitude'
      latitudeProp = 'returnLatitude'
    }
    if (formVal[longitudeProp] && formVal[latitudeProp]) {
      formRef.value.clearValidate(type)
    } else {
      formRef.value.setFields({
        [`${type}`]: {
          status: 'error',
          message: '当前位置无法定位，将会影响费用计算。请选择具体取车地址或地图中选取地址',
        },
      })
    }
  }
  // 选择车型
  const carModelSelectorRef = ref()
  const selectCarModelFn = () => {
    if (formDisabled) return
    if (props.isProgress) return
    if (form.value.rentDays && form.value.siteId) {
      const param = {
        siteId: form.value.siteId,
        modelId: form.value.originalModelId,
        // 默认7天
        dateRange: form.value.timeRange,
      }
      console.log(param)
      carModelSelectorRef.value.open(param)
    } else {
      Message.error('请先选择租赁周期和取车门店后，再选择车型')
    }
  }
  // 车型选择完成
  const carModelConfirmFn = (id, option) => {
    form.value.originalModelId = id
    form.value.originalModelName = option.modelName

    // 判断当前排车车型是否和当前车型一致，符合则无变化，不符合则车牌号清空
    if (form.value.carModelId && form.value.carModelId !== id) {
      // 清空车辆信息
      form.value.carId = undefined
      form.value.licenseNo = undefined
      form.value.carModelId = undefined
      form.value.carModelName = undefined
    }

    // 去除校验文本
    formRef.value.clearValidate('originalModelId')
  }
  // 清空车型
  const clearCarModelFn = () => {
    form.value.originalModelId = undefined
    form.value.originalModelName = undefined
  }

  // 取车门店长租配置
  const siteLongSiteConfig = ref({})
  // 还车门店长租配置
  const returnSiteLongSiteConfig = ref({})
  // 上门送车开关是否可选
  const sendServiceFlagDisabled = computed(() => {
    return !siteLongSiteConfig.value.isOnsiteService
  })
  // 上门取车开关是否可选
  const returnServiceFlagDisabled = computed(() => {
    return !returnSiteLongSiteConfig.value.isOnsiteService
  })
  // 清空 address 相关值
  const clearAddress = (type = 'address') => {
    formRef.value.clearValidate(type)
    // if (type == 'address') {
    form.value.sendServiceFlag = false
    form.value.address = undefined
    form.value.longitude = undefined
    form.value.latitude = undefined
    // } else {
    form.value.returnServiceFlag = false
    form.value.returnAddress = undefined
    form.value.returnLongitude = undefined
    form.value.returnLatitude = undefined
    // }
  }
  // 切换门店
  const prevSiteId = ref()
  const orderInfo = inject('orderInfo')
  const changeSiteIdFn = (val, type) => {
    new Promise((resolve) => {
      if (props.mode == 'editOrder' && type == 'site') {
        // 编辑订单，修改取车门店
        Modal.confirm({
          title: '确认',
          content: '变更取车门店，系统将重置车型和车牌号，请确认是否修改？',
          okText: '确认',
          cancelText: '关闭',
          onCancel: () => {
            if (prevSiteId.value) {
              form.value.siteId = prevSiteId.value
            } else {
              form.value.siteId = orderInfo.value.siteId
            }
          },
          onOk: () => {
            prevSiteId.value = val
            resolve()
          },
        })
      } else {
        resolve()
      }
    }).then(() => {
      if (type == 'site') {
        // 切换取车门店，需要清空车型和车牌
        form.value.originalModelId = undefined
        form.value.originalModelName = undefined
        form.value.carId = undefined
        form.value.licenseNo = undefined
        form.value.carModelId = undefined
        form.value.carModelName = undefined
      }
      getSiteLongConfig(val, (longSiteConfig) => {
        type == 'site' ? (siteLongSiteConfig.value = longSiteConfig) : (returnSiteLongSiteConfig.value = longSiteConfig)
        nextTick(() => {
          if (type == 'site') {
            // 当前选中
            if (form.value.sendServiceFlag && sendServiceFlagDisabled.value) {
              clearAddress('address')
            }
          } else {
            if (form.value.returnServiceFlag && returnServiceFlagDisabled.value) {
              clearAddress('returnAddress')
            }
          }
        })
      })
    })
  }
  // 读取门店租赁配置
  const getSiteLongConfig = (id, callback) => {
    // 获取门店租赁配置详情
    getSiteLeaseDetail({ id }).then(({ result }) => {
      let config = result.longSiteConfig || {}
      callback(config)
    })
  }
  // 还车门店列表获取
  const returnSiteListGetFn = (list) => {
    if (list.length > 0) {
      if (!list.find((site) => site.id == form.value.returnSiteId)) {
        clearReturnSite()
      }
    } else {
      clearReturnSite()
    }
  }
  // 清空还车门店相关配置
  const clearReturnSite = () => {
    form.value.returnSiteId = undefined
    form.value.returnSiteName = undefined
    form.value.returnServiceFlag = false
    form.value.returnAddress = undefined
    form.value.returnLongitude = undefined
    form.value.returnLatitude = undefined

    returnSiteLongSiteConfig.value = {}
    formRef.value.clearValidate('returnAddress')
  }
  // 编辑场景下，更新 LongsiteConfig
  const updateLongsiteConfig = (siteId, typeList) => {
    let formValue = form.value
    // 上门取送车开关默认值
    for (var i = 0; i < typeList.length; i++) {
      let type = typeList[i]
      if (type == 'site') {
        if (formValue.sendServiceFlag) {
          siteLongSiteConfig.value = { isOnsiteService: true }
          typeList.splice(i, 1)
          i--
        }
      } else {
        if (formValue.returnServiceFlag) {
          returnSiteLongSiteConfig.value = { isOnsiteService: true }
          typeList.splice(i, 1)
          i--
        }
      }
    }
    if (typeList.length > 0) {
      // 获取门店租赁配置详情
      getSiteLongConfig(siteId, (longSiteConfig) => {
        // 父组件读取长租配置后
        typeList.forEach((type) => {
          if (type == 'site') {
            siteLongSiteConfig.value = longSiteConfig
          } else {
            returnSiteLongSiteConfig.value = longSiteConfig
          }
        })
      })
    }
  }
  defineExpose({
    updateLongsiteConfig,
  })
</script>
<style lang="less" scoped>
  .rent-days {
    color: rgb(var(--primary-6));
  }
  .map-location {
    color: rgb(var(--primary-6));
    font-size: 14px;
    cursor: pointer;
    svg {
      color: rgb(var(--primary-6));
    }
  }
  .map-location.disabled {
    cursor: no-drop;
    color: rgba(24, 144, 255, 0.5);
    svg {
      color: rgba(24, 144, 255, 0.5);
    }
  }
  .quick-date-list {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
    .quick-date-item {
      height: 24px;
      line-height: 22px;
      border-radius: 2px 2px 2px 2px;
      opacity: 1;
      border: 1px solid #dadbdd;
      padding: 0 12px;
      cursor: pointer;
      font-size: 12px;
      color: #55585f;
      &.active {
        background: #e0edff;
        border: 1px solid #3072f6;
        font-weight: 600;
        color: #3072f6;
      }
    }
  }

  .hideError {
  }
</style>
